package manager

import (
	"context"
	"go.uber.org/zap"
	apiAuth "navi-mumbai/app/api/admin/internal/auth"
	"navi-mumbai/app/api/admin/internal/model/pg"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/xerr"
	"time"

	"navi-mumbai/app/api/admin/internal/svc"
	"navi-mumbai/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetManagerLogListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetManagerLogListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetManagerLogListLogic {
	return &GetManagerLogListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetManagerLogListLogic) GetManagerLogList(req *types.GetManagerLogListReq) (resp *types.GetManagerLogListResp, err error) {
	// verify permission level
	adminUid := ctxdata.GetUidFromCtx(l.ctx)
	level := ctxdata.GetAdminPermissionLevelFromCtx(l.ctx)
	if !l.svcCtx.Auth.VerifyPermissionLevel(l.ctx, apiAuth.SuperAdminQueryManagerLogListApi, adminUid, level) {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.AuthFail, "permission denied")
	}

	var start, end *time.Time
	if req.StartTime != "" {
		var t time.Time
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err = time.ParseInLocation(dbkey.DateTimeCNFormat, req.StartTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "invalid start time")
		}
		start = &t
	}

	if req.EndTime != "" {
		var t time.Time
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err = time.ParseInLocation(dbkey.DateTimeCNFormat, req.EndTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "invalid end time")
		}
		end = &t
	}

	var list []*pg.ApiLog
	list, err = l.svcCtx.ApiLogModel.Find(l.ctx, req.Uid, start, end, req.PageNo, req.PageSize)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	resp = &types.GetManagerLogListResp{
		List: make([]*types.ManagerLog, 0),
	}
	if len(list) == 0 {
		return
	}

	if req.PageNo <= 1 {
		resp.Total, err = l.svcCtx.ApiLogModel.Count(l.ctx, req.Uid, start, end)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	}

	for i := 0; i < len(list); i++ {
		var vl types.ManagerLog
		vl.Id = list[i].Id
		vl.Uid = list[i].Uid
		vl.Api = list[i].Api
		vl.ReqParam = list[i].ReqParam
		vl.RespParam = list[i].Response
		vl.CreateTime = list[i].CreateTime.Format(dbkey.DateTimeCNFormat)

		resp.List = append(resp.List, &vl)
	}
	return
}
